package com.lihepeng.leecode.juc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入锁 案例
 */
class Send{
    public synchronized void sendSMS(){
        System.out.println(Thread.currentThread().getName()+"发送短信");
        sendEmail();
    }
    public synchronized void sendEmail() {
        System.out.println(Thread.currentThread().getName()+"发送邮件");
    }

}
class SendV2 implements Runnable{
    Lock lock = new ReentrantLock();
    public void get(){
        lock.lock();
        try {
           System.out.println(Thread.currentThread().getName()+"获得锁");
           setLock();
       }catch (Exception e) {
            e.printStackTrace();
       }finally {
           lock.unlock();
       }

    }
    public  void setLock() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"加锁");
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    @Override
    public void run() {
        get();
    }
}
public class ReenterLockDemo {
    public static void main(String[] args) {
//        Send send = new Send();
//        Thread t1 = new Thread(() -> {
//            send.sendSMS();
//        }, "t1");
//        Thread t2 = new Thread(() -> {
//            send.sendSMS();
//        }, "t2");
//        t1.start();
//        t2.start();
        Thread t1 = new Thread(new SendV2(),"t3");
        Thread t2 = new Thread(new SendV2(),"t4");
        t1.start();
        t2.start();
    }
}
